<template>
  <div class="app-container">
    <el-drawer title="搜索" :visible.sync="search" v-if="search" size="330px"  align="center">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出差编号" prop="tripcode">
        <el-input
          v-model="queryParams.tripcode"
          placeholder="请输入出差编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出差人" prop="triper">
        <el-input
          v-model="queryParams.triper"
          placeholder="请输入出差人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始日期" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否审核" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否审核" clearable>
          <el-option
            v-for="dict in dict.type.bs_trip_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-drawer>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['demo:trips:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['demo:trips:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
        >搜索</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="tripsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" align="center" prop="id" v-if="false"/>
      <el-table-column label="出差标题" align="center" prop="title" width="180"/>
      <el-table-column label="出差编号" align="center" prop="tripcode" width="180"/>
      <el-table-column label="出差人" align="center" prop="triper" />
      <el-table-column label="目的地" align="center" prop="address" />
      <el-table-column label="时长" align="center" prop="days" />
      <el-table-column label="开始日期" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="actBusinessStatus.status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.act_status" :value="scope.row.actBusinessStatus.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否审核" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bs_trip_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="340">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status===1 && scope.row.actBusinessStatus.status==='draft'"
            size="mini"
            type="warning"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['demo:trips:edit']"
            style="width: 60px"
          >修改</el-button>
          <el-button
            v-if="scope.row.status===1 && scope.row.actBusinessStatus.status==='draft'"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['demo:trips:remove']"
            style="width: 60px"
          >删除</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status==='waiting'"
            size="mini"
            type="warning"
            icon="el-icon-back"
            @click="cancelProcessApply(scope.row)"
            style="width: 60px"
          >撤销</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status!=='draft'"
            size="mini"
            type="primary"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            style="width: 60px"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出差信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-tabs  type="border-card" >
        <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="出差标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入出差标题" />
            </el-form-item>
            <el-form-item label="出差内容" prop="content">
              <el-input v-model="form.content" placeholder="请输入出差内容" />
            </el-form-item>
            <el-form-item label="出差人" prop="triper">
              <el-input v-model="form.triper" placeholder="请输入出差人" />
            </el-form-item>
            <el-form-item label="目的地" prop="address">
              <el-input v-model="form.address" placeholder="请输入目的地" />
            </el-form-item>
            <el-form-item label="时长" prop="days">
              <el-input v-model="form.days" placeholder="请输入时长" />
            </el-form-item>
            <el-form-item label="开始日期" prop="startTime">
              <el-date-picker clearable
                v-model="form.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期" prop="endTime">
              <el-date-picker clearable
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="是否审核" prop="status">
              <el-select v-model="form.status" placeholder="请选择是否审核" disabled="true">
                <el-option
                  v-for="dict in dict.type.bs_trip_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="dialog-footer" style="float:right" v-if="flag">
            <el-button :loading="buttonLoading" type="success" @click="submitForm('zancun')">暂存</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')">提交</el-button>
            <el-button @click="cancel" type="danger">取 消</el-button>
          </div>
        </el-tab-pane>
        <!-- 审批历史 -->
        <el-tab-pane label="审批历史" v-if="processInstanceId">
          <history ref="historyRef" :processInstanceId="processInstanceId" ></history>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 提交 -->
    <verify ref="verifyRef" @callSubmit="callSubmit" :taskId="taskId" :taskVariables="taskVariables" :sendMessage="sendMessage"></verify>
  </div>
</template>

<script>
import { listTrips, getTrips, delTrips, addTrips, updateTrips } from "@/api/demo/trips";
import processAip from "@/api/workflow/processInst";
import history from "@/components/Process/History";
import verify from "@/components/Process/Verify";

export default {
  name: "Trips",
  dicts: ['bs_trip_status','act_status'],
  components: {
    history,
    verify
  },
  data() {
    return {
      // 流程实例
      processInstanceId: '',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      search:false,
      showSearch: true,
      // 总条数
      total: 0,
      // 出差信息表格数据
      tripsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        tripcode: undefined,
        content: undefined,
        triper: undefined,
        address: undefined,
        days: undefined,
        startTime: undefined,
        endTime: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "出差标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "出差内容不能为空", trigger: "blur" }
        ],
        triper: [
          { required: true, message: "出差人不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "目的地不能为空", trigger: "blur" }
        ],
        days: [
          { required: true, message: "时长不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始日期不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束日期不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "是否同意不能为空", trigger: "change" }
        ],
      },
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 搜索按钮操作 */
    handleSearch() {
      this.search = true;
    },
    /** 查询出差信息列表 */
    getList() {
      this.loading = true;
      listTrips(this.queryParams).then(response => {
        this.tripsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        tripcode: undefined,
        content: undefined,
        triper: undefined,
        address: undefined,
        days: undefined,
        startTime: undefined,
        endTime: undefined,
        status: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.search = false
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出差信息";
      this.form.status = 1;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.flag = true
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getTrips(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.$nextTick(() => {
          this.processInstanceId=response.data.processInstanceId
        })
        this.open = true;
        this.title = "修改";
        this.sendMessage = {
          title:'出差申请',
          messageContent:'出差申请{'+row.id+"["+row.tripcode+"]}"
        }
      });
    },
    // 提交成功回调
    callSubmit(){
      //查询ActBusinessStatus
      processAip.getInfoByBusinessKey(this.businessKey).then(response => {
        console.log(response)
        // updateTrips(response);
        this.open = false;
        this.getList();
      })

    },
    /** 提交按钮 */
    submitForm(flag) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateTrips(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              if(flag === 'submit'){
                this.submitFormAppply(response.data)
              }
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTrips(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    //提交流程
    submitFormAppply(entity){
      let variables = {
        entity: entity
      }
      const data = {
        processKey: 'trip', // key
        businessKey: entity.id, // 业务id
        variables: variables,
        classFullName: 'com.ruoyi.demo.domain.BsTrip'
      }
      // 启动流程
      let assigneeList = []
      assigneeList.push(1)
      assigneeList.push(2)
      processAip.startProcessApply(data).then(response => {
        this.taskId = response.data.taskId;
        // 查询下一节点的变量
        this.taskVariables = {
          entity: entity,  // 变量
          //assignee: '1', // key
          //assigneeList: assigneeList
        }
        this.$refs.verifyRef.visible = true
        this.$refs.verifyRef.reset()
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除出差信息编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delTrips(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/trips/export', {
        ...this.queryParams
      }, `trips_${new Date().getTime()}.xlsx`)
    },
    cancelProcessApply(row){
      this.$modal.confirm('是否撤销申请').then(() => {
        this.loading = true;
        return processAip.cancelProcessApply(row.processInstanceId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    //查看
    handleView(row){
      this.flag = false
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getTrips(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.$nextTick(() => {
          this.processInstanceId=response.data.processInstanceId
        })
        this.open = true;
        this.title = "查看请假业务";
      });
    },
  }
};
</script>
